package cn.tedu.charging.order.config;

import cn.tedu.charging.order.mapper.BillSuccessMapper;
import cn.tedu.charging.order.mqtt.MqttContext;
import cn.tedu.charging.order.mqtt.MqttMyCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.UUID;

@Configuration
public class MqttClientConfiguration {
    @Value("${charging.emqx.address}")
    private String address;
    @Value("${charging.emqx.username}")
    private String username;
    @Value("${charging.emqx.password}")
    private String password;
    @Autowired
    private MqttContext mqttContext;
    @Bean
    public MqttClient mqttClientInit(){
        //客户端类似rabbtimq里使用工厂 生成的connection长连接
        MqttClient mqttClient = null;
        try{
            //给对象初始化赋值 实例化对象 告诉客户端 emqx地址address
            //并且客户端对象的id值要保证唯一
            mqttClient= new MqttClient(address, UUID.randomUUID().toString(),new MemoryPersistence());
            //客户端初始化实例化完成 需要额外的选项参数 完善我们对客户端的需求定义
            MqttConnectOptions options=new MqttConnectOptions();
            //必须加的 username password
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            mqttClient.setCallback(new MqttMyCallback(mqttClient,mqttContext));
            //开始发起连接
            mqttClient.connect(options);
        }catch (Exception e){
            e.printStackTrace();
        }
        return mqttClient;
    }
}
